<template>
    <view class="container">
        <!-- 顶部标题栏 -->
        <view class="header">
            <text class="title">第 {{ roundNumber }} 局结算</text>
            <view class="divider"></view>
        </view>

        <!-- 加载状态 -->
        <view v-if="loading" class="loading-state">
            <uni-load-more status="loading"></uni-load-more>
        </view>
        
        <!-- 错误提示 -->
        <view v-if="error" class="error-state">
            <image src="@/static/logo.png" class="error-icon"></image>
            <text class="error-text">{{ error }}</text>
            <button class="retry-button" @click="getRoomUsers">重试</button>
        </view>

        <!-- 主要内容区域 -->
        <view v-if="!loading && !error" class="content">
            <!-- 玩家结算卡片列表 -->
            <view class="player-cards">
                <view v-for="(player, index) in players" :key="player.userId" class="player-card">
                    <!-- 玩家头像和信息 -->
                    <view class="player-info">
                        <image :src="player.avatar || defaultAvatar" class="avatar"></image>
                        <text class="player-name">{{ player.nickname }}</text>
                    </view>
                    
                    <!-- 分数输入区域 -->
                    <view class="score-section">
                        <text class="score-label">得分:</text>
                        <input 
                            type="number" 
                            v-model="player.score" 
                            placeholder="0"
                            class="score-input"
                            @input="validateScore(player)"
							:disabled="player.userId !== currentUserId" 
							:class="{ 'disabled-input': player.userId !== currentUserId }"
                        />
                    </view>
                    
                    <!-- 赢家选择 -->
                    <view class="winner-section">
                        <text class="winner-label">赢家:</text>
                        <switch 
                            :checked="player.isWinner" 
                            @change="handleWinnerChange(player.userId, $event.detail.value)"
                            color="#07C160"
                            class="winner-switch"
                        />
                    </view>
                </view>
            </view>
            
            <!-- 结算说明 -->
            <view class="settlement-info">
                <text class="info-text">结算规则：赢家只获得收入，非赢家需向赢家支付等额于其收入的分数</text>
            </view>
            
            <!-- 底部操作栏 -->
            <view class="action-bar">
                <button class="action-button secondary" @click="backbutton">
                    <text>取消</text>
                </button>
				
                <button 
                  class="action-button primary" 
                  @click="confirmbutton" 
                  :disabled="isSubmitting || !allScoresFilled" 
                >
                  <template v-if="!isSubmitting">
                    <!-- 未填完或提交中均禁用未填完时显示提示，填完后显示“确认结算” -->
                    <text v-if="allScoresFilled">确认结算</text>
                    <text v-else>等待其他用户输入</text>
                  </template>
                  <text v-else>提交中...</text>
                </button>
				
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
// 引入 Pinia 的 socketStore，用于全局 Socket 连接管理
import { storeToRefs } from 'pinia';
import { useSocketStore } from '@/stores/modules/socketStore.js';



// 初始化 Socket 状态管理实例
const socketStore = useSocketStore();
const { connectionState } = storeToRefs(socketStore); // 解构连接状态（响应式）

// 默认头像
const defaultAvatar = 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/unicloudlogo.png';

// 新增：计算是否所有玩家都填写了有效分数
const allScoresFilled = computed(() => {
  // 遍历所有玩家，检查每个分数是否为有效数值（非空、非NaN、>=0）
  return players.value.every(player => {
    const score = parseInt(player.score);
    return player.score !== '' && !isNaN(score) && score >= 0;
  });
});

const currentUserId = JSON.parse(uni.getStorageSync('user')).userinfo.userid; 
// console.log("currentUserId",currentUserId)
// 响应式数据
const loading = ref(true);
const error = ref(null);
const isSubmitting = ref(false);
const roundNumber = ref(0);
const players = ref([]);
const roomId = ref('');

onLoad((options) => {
    // console.log(options)
    roomId.value = options.roomId;
    roundNumber.value = parseInt(options.roundNumber) || 0;
    getRoomUsers();// 获取对局详情
});

// 获取房间内用户
const getRoomUsers = async () => {
    try {
        loading.value = true;
        error.value = null;
        const res = await uni.request({
              url: `http://172.16.24.120:5000/mysqlroom/getroomusers`,
              method: 'GET',
              data: {
                roomId: roomId.value,
                roundNumber: roundNumber.value
              }
            });     
        
        if (res.statusCode === 200) {
            // 初始化玩家数据，添加分数和赢家状态
            players.value = res.data.players.map(p => ({
                ...p,
				// userId: p.userId,
				// avatar: p.avatar,
				// nickname: p.nickname,
                score: "0",  // 默认为0而非空
                isWinner: false
            }));
        } else {
            throw new Error('获取房间数据失败');
        }
    } catch (err) {
        error.value = err.message || '加载数据失败，请稍后重试';
        console.error('获取房间数据出错:', err);
    } finally {
        loading.value = false;
    }
};

// 验证分数输入 - 确保为正数
const validateScore = (player) => {
    // 移除非数字字符和负号
    player.score = player.score.replace(/[^\d]/g, '');
    // 确保至少为0
    if (!player.score) player.score = "0";
    // 限制数字范围
    const num = parseInt(player.score) || 0;
    if (num > 500) player.score = '500';
    // if (num < 0) player.score = '0';  // 确保不会出现负数
};

// 赢家处理逻辑
const handleWinnerChange = (userId, isWinner) => {
    // 如果要设置为赢家，先取消其他所有玩家的赢家状态
    if (isWinner) {
        players.value.forEach(p => {
            if (p.userId !== userId) {
                p.isWinner = false;
            }
        });
    }
    // 设置当前玩家的赢家状态
    const player = players.value.find(p => p.userId === userId);
    if (player) {
        player.isWinner = isWinner;
        // 赢家默认最少赢20分
        // if (isWinner && (!player.score || parseInt(player.score) < 20)) {
        //     player.score = '20';
        // }
    }
};

// 提交数据 - 根据新结算规则修改
const confirmbutton = async () => {
    try {
        isSubmitting.value = true;
	    // 先检查是否所有分数已填写（与allScoresFilled一致，双重保障）
	    if (!allScoresFilled.value) {
	      uni.showToast({
	        title: '请等待所有玩家填写分数',
	        icon: 'none'
	      });
	      return;
	    }
		
        // 1. 验证数据 - 检查所有玩家都有有效分数
        const invalidPlayers = players.value.filter(p => 
            p.score === '' || isNaN(parseInt(p.score)) || parseInt(p.score) < 0
        );
        if (invalidPlayers.length > 0) {
            uni.showToast({
                title: '请为所有玩家输入有效的正数分数',
                icon: 'none'
            });
            return;
        }
        // 2. 验证只有一个赢家
        const winners = players.value.filter(p => p.isWinner);
        if (winners.length !== 1) {
            uni.showToast({
                title: '必须且只能指定一个赢家',
                icon: 'none'
            });
            return;
        }

        // 3. 准备提交数据
        // 赢家: 只收入分数(+winnerScore)
        // 非赢家: 收入自己的分数，但要支出与自己收入等额的分数给赢家(实际收益为 0)
        const submitData = {
            roomId: roomId.value,
            roundNumber: roundNumber.value,
            players: players.value.map(p => ({
                userId: p.userId,
                score: parseInt(p.score),  // 转换为数字
                isWinner: p.isWinner
            }))
        };
        
        // 4. 提交数据到服务器
        const res = await uni.request({
              url: 'http://172.16.24.120:5000/mysqlroom/rounds/settle',
              method: 'POST',
              data: submitData
            });
        if (res.statusCode === 200) {
              uni.showToast({ title: '结算成功' });
              setTimeout(() => uni.navigateBack(), 1500);
        } 
		else {
            // throw new Error('提交分数失败');
			uni.showToast({
			    title: res.message || '提交分数失败',
			    icon: 'none'
			});
        }
    } catch (err) {
		console.log(err)
        uni.showToast({
            title: err.message || '提交分数失败',
            icon: 'none'
        });
    } finally {
        isSubmitting.value = false;
    }
};

// 返回按钮
const backbutton = () => {
    uni.navigateBack();
};
</script>

<style scoped>
/* 全局容器样式 */
.container {
    padding: 0;
    background-color: #f8f8f8;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
}

/* 头部样式 */
.header {
    padding: 20px 16px 12px;
    background-color: #ffffff;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.title {
    font-size: 20px;
    font-weight: 600;
    color: #333;
    text-align: center;
}

.divider {
    height: 1px;
    background-color: #eee;
    margin-top: 12px;
}

/* 加载状态样式 */
.loading-state {
    padding: 40px 0;
    display: flex;
    justify-content: center;
}

/* 错误状态样式 */
.error-state {
    padding: 40px 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.error-icon {
    width: 60px;
    height: 60px;
    margin-bottom: 16px;
}

.error-text {
    font-size: 16px;
    color: #ff4d4f;
    margin-bottom: 20px;
    text-align: center;
}

.retry-button {
    background-color: #1890ff;
    color: white;
    border: none;
    border-radius: 20px;
    padding: 8px 24px;
    font-size: 14px;
}

/* 主要内容区域 */
.content {
    flex: 1;
    padding: 16px;
    display: flex;
    flex-direction: column;
}

/* 结算说明 */
.settlement-info {
    padding: 12px 16px;
    background-color: #fff8e6;
    border-radius: 8px;
    margin: 10px 0;
}

.info-text {
    font-size: 14px;
    color: #e6a23c;
    line-height: 1.5;
}

/* 玩家卡片列表 */
.player-cards {
    flex: 1;
}

.player-card {
    background-color: #fff;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 12px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.player-info {
    display: flex;
    align-items: center;
    flex: 1;
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 12px;
}

.player-name {
    font-size: 16px;
    color: #333;
    font-weight: 500;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100px;
}

/* 分数输入区域 */
.score-section {
    display: flex;
    align-items: center;
    margin: 0 16px;
}

.score-label {
    font-size: 14px;
    color: #666;
    margin-right: 8px;
}

.score-input {
    width: 80px;
    height: 36px;
    border: 1px solid #ddd;
    border-radius: 6px;
    padding: 0 10px;
    text-align: center;
    font-size: 16px;
    color: #333;
    background-color: #f9f9f9;
}

/* 赢家选择区域 */
.winner-section {
    display: flex;
    align-items: center;
}

.winner-label {
    font-size: 14px;
    color: #666;
    margin-right: 8px;
}

.winner-switch {
    transform: scale(0.8);
}

/* 底部操作栏 */
.action-bar {
    display: flex;
    justify-content: space-between;
    padding: 16px;
    background-color: #fff;
    border-top: 1px solid #eee;
    position: sticky;
    bottom: 0;
}

.action-button {
    flex: 1;
    height: 48px;
    border-radius: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    font-weight: 500;
    transition: all 0.3s;
}

.action-button.secondary {
    background-color: #f5f5f5;
    color: #666;
    margin-right: 12px;
}

.action-button.secondary:active {
    background-color: #e5e5e5;
}

.action-button.primary {
    background-color: #07C160;
    color: white;
}

.action-button.primary:disabled {
    background-color: #a0d7b8;
    opacity: 0.7;
}

.action-button.primary:active:not(:disabled) {
    background-color: #05a14e;
}
/* 非当前用户的输入框样式（灰色、不可点击） */
.disabled-input {
  background-color: #f0f0f0;
  color: #999;
  cursor: not-allowed;
}
</style>
